﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.ServiceProcess;
using System.Diagnostics;

namespace Sinacor.OMM.Receptor.KeepUp
{
    public partial class KeepUp : Form
    {
        static Thread _startThread;
        
        const string _serviceName = "BM&FBOVESPA Receptor Service";
        const int _timeout = 60000;

        public KeepUp()
        {
            InitializeComponent();

            _startThread = new Thread(new ThreadStart(Run));
            _startThread.Start();
        }

        private static void Run()
        {
            try
            {
                StopService(_serviceName, _timeout);
                StartService(_serviceName, _timeout);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Receptor.KeepUp", ex.Message, EventLogEntryType.Error);
            }
            finally
            {
                Application.Exit();
            }
        }

        public static void StartService(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = new ServiceController(serviceName);
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        public static void StopService(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = new ServiceController(serviceName);
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
    }
}
